package com.library.lms.controller;

import com.library.lms.entity.User;
import com.library.lms.service.UserService;
import com.library.lms.utils.IdentifyCodeUtils;
import com.library.lms.utils.JwtUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.awt.image.BufferedImage;
import java.util.HashMap;
import java.util.Map;

@RestController
@Slf4j
@RequestMapping()
public class loginController {

    @Resource
    public UserService userService;


    @PostMapping("/login")
    public Map<String,Object> login(@ModelAttribute("user") User user){
        Map<String, Object> map = new HashMap<>();
        Map<String, String> tokenMap = new HashMap<>();
        String password = DigestUtils.md5DigestAsHex(user.getPassword().getBytes());
        log.info("看看[{}]",password);
        try {
            User u = userService.selectUser(user.getName(), password);
            tokenMap.put("id",u.getId().toString());
            tokenMap.put("name", u.getName());
            //识别管理员还是普通用户
            map.put("type", u.getType());
            log.info(u.toString());
            log.info("请求的数据"+user.toString());
            //生成token
            String token = JwtUtil.getToken(tokenMap);
            map.put("token", token);
            map.put("name", u.getName());
            map.put("id", u.getId());
            map.put("uType", u.getType());
            map.put("msg", "success");
        }catch (Exception e) {
            e.printStackTrace();
            map.put("msg", "fail");
            return map;
        }

        return map;
    }

    @GetMapping("/kaptcha")
    public void identifyImage(HttpServletResponse response, HttpServletRequest request){
        //创建随机验证码
        IdentifyCodeUtils utils = new IdentifyCodeUtils();
        String identifyCode = utils.getIdentifyCode();
        //session存入验证码
        log.info("验证码[{}]",identifyCode);
        HttpSession session = request.getSession(true);
        session.setAttribute("code", identifyCode);
        //根据验证码创建图片
        BufferedImage identifyImage = utils.getIdentifyImage(identifyCode);
        //回传给前端
        utils.responseIdentifyImg(identifyImage,response);

    }


}
